<script setup>
import PageContainer from "@/components/PageContainer.vue";
import { ref } from "vue";
import { useUserStore } from "@/stores/index";
import { userUpdatePasswordService } from "@/api/user";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const userStore = useUserStore()
const formRef = ref()
const pwdForm = ref({
  oldPwd: userStore.user.password,
  newPwd: null,
  rePwd: null
})
const rules = {
  newPwd: [{ required: true, message: "请输入新密码", trigger: 'blur' },
  {
    validator: (rule, value, callback) => {
      if (value === pwdForm.value.oldPwd) {
        callback(new Error("新密码必须不同于原密码"))
      } else {
        callback()
      }
    }, trigger: 'blur'
  }
  ],
  rePwd: [{ required: true, message: "请再次输入新密码", trigger: 'blur' },
  {
    validator: (rule, value, callback) => {
      if (value !== pwdForm.value.newPwd) {
        callback(new Error("两次密码不一致"))
      } else {
        callback()
      }
    },
    trigger: 'blur'
  }
  ]
}
// 更新用户密码
const router = useRouter()
const submitPwd = async () => {
  await formRef.value.validate()
  await userUpdatePasswordService(pwdForm.value)
  ElMessage.success("修改密码成功")
  // 退出登录
  userStore.setToken('')
  userStore.setUser({})
  router.push("/login")
}
</script>

<template>
  <PageContainer title="修改密码">
    <el-form :model="pwdForm" :rules="rules" ref="formRef">
      <el-form-item label="原密码">
        <el-input style="width: 1100px" v-model="pwdForm.oldPwd" disabled></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input style="width: 1100px" v-model="pwdForm.newPwd"></el-input>
      </el-form-item>
      <el-form-item label="再次确认密码" class="end-item" prop="rePwd">
        <el-input class="end-input" v-model="pwdForm.rePwd"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitPwd">修改密码</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </PageContainer>
</template>
<style scoped>
/* .el-form-item {
  margin-left: 10px;
} */
/*
:deep(.el-form-item.asterisk-left.el-form-item--label-right) {
  transform: translate(-39px, 0px);
} */
.end-item {
  transform: translate(-40px, 0px);
}
</style>
<style>
.el-card__body {
  margin-left: 20px
}
</style>
